from framework.common.pt_logger import logger
from framework.core.crawler_task import Task
from framework.core.sqs_task_pool import SQSTaskPool
from jobs.amazon.util import sqs_util


def setup_task_pool(name):
    pool_name = "pt-spider-serverless-%s-queue" % name
    task_pool = SQSTaskPool(name=pool_name)
    sqs_util.create_if_not_existed(queue_name=pool_name)
    return task_pool


def start_initiator(metadata=None, payload=None):
    batch_id = metadata["time"].split("T")[0]
    task_type = payload["tt"]

    task_pool = setup_task_pool(task_type)
    count = sqs_util.check_sqs_remain_message_count(task_pool.queue_name)
    # there are 24 departments that are allowed to run together
    if count and int(count) <= 0:
        init_tasks_map = {
            "CoreProductsBestSellers": [("https://www.amazon.com/Best-Sellers-Appliances/zgbs/appliances", {"batchId": batch_id, "SpiderName": "CoreProductsSpider", "tt": "CoreProductsBestSellers", "td": "init", "tp": "first_page"}, None, None)],
            "CoreProductsMostWishedFor": [("https://www.amazon.com/gp/most-wished-for/appliances", {"batchId": batch_id, "SpiderName": "CoreProductsSpider", "tt": "CoreProductsMostWishedFor", "td": "init", "tp": "first_page"}, None, None)],
            "CoreProductsGiftIdeas": [("https://www.amazon.com/gp/most-gifted/appliances", {"batchId": batch_id, "SpiderName": "CoreProductsSpider", "tt": "CoreProductsGiftIdeas", "td": "init", "tp": "first_page"}, None, None)],
            "CoreProductsMoversAndShakers": [("https://www.amazon.com/gp/movers-and-shakers/appliances", {"batchId": batch_id, "SpiderName": "CoreProductsSpider", "tt": "CoreProductsMoversAndShakers", "td": "init", "tp": "first_page"}, None, None)],
            "CoreProductsNewReleases": [("https://www.amazon.com/gp/new-releases/appliances", {"batchId": batch_id, "SpiderName": "CoreProductsSpider", "tt": "CoreProductsNewReleases", "td": "init", "tp": "first_page"}, None, None)],
        }
        init_tasks = Task.create_tasks(init_tasks_map[task_type], parser="default", parent_result=None)
        task_pool.enqueue(init_tasks)
    else:
        logger.warning("there are still %s messages in the queue %s, please purge the queue and restart" % (count, task_pool.queue_name))